<template>
    <!--
        附件控件
    -->
    <div id = "fileWidgetBody">
        <b-card
            title=""
            :img-src="fileWidgetForm.attachmentPic"
            img-alt="Image"
            img-top
            tag="article"
            style="max-width: 18rem;min-width: 18rem;"
            class="mb-2"
        >
            <b-card-text>
                <a href="javascript:;" @click="showFileUpload()" v-if="canUpload == true" class="btn btn-sm btn-clean btn-icon" title="上传">	                            
                    <span class="svg-icon svg-icon-primary svg-icon-2x">
                        <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24px" height="24px" viewBox="0 0 24 24" version="1.1">
                        <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                            <polygon points="0 0 24 0 24 24 0 24"/>
                            <rect fill="#000000" opacity="0.3" x="11" y="3" width="2" height="14" rx="1"/>
                            <path d="M6.70710678,10.7071068 C6.31658249,11.0976311 5.68341751,11.0976311 5.29289322,
                            10.7071068 C4.90236893,10.3165825 4.90236893,9.68341751 5.29289322,9.29289322 L11.2928932,
                            3.29289322 C11.6714722,2.91431428 12.2810586,2.90106866 12.6757246,3.26284586 L18.6757246,
                            8.76284586 C19.0828436,9.13603827 19.1103465,9.76860564 18.7371541,10.1757246 C18.3639617,10.5828436 17.7313944,10.6103465 17.3242754,10.2371541 L12.0300757,5.38413782 L6.70710678,10.7071068 Z" fill="#000000" fill-rule="nonzero"/>
                            <rect fill="#000000" opacity="0.3" x="3" y="19" width="18" height="2" rx="1"/>
                        </g>
                    </svg>
                    </span>						
                </a>
                <a href="javascript:;" @click="downloadFile()" class="btn btn-sm btn-clean btn-icon" title="下载" >	                            
                    <span class="svg-icon svg-icon-primary svg-icon-2x">
                        <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24px" height="24px" viewBox="0 0 24 24" version="1.1">
                            <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                                <rect x="0" y="0" width="24" height="24"/>
                                <path d="M2,13 C2,12.5 2.5,12 3,12 C3.5,12 4,12.5 4,13 C4,13.3333333 4,15 4,18 C4,
                                19.1045695 4.8954305,20 6,20 L18,20 C19.1045695,20 20,19.1045695 20,18 L20,13 C20,12.4477153 20.4477153,12 21,12 C21.5522847,12 22,12.4477153 22,13 L22,18 C22,20.209139 20.209139,22 18,22 L6,22 C3.790861,22 2,20.209139 2,18 C2,15 2,13.3333333 2,13 Z" fill="#000000" fill-rule="nonzero" opacity="0.3"/>
                                <rect fill="#000000" opacity="0.3" transform="translate(12.000000, 8.000000) rotate(-180.000000) translate(-12.000000, -8.000000) " x="11" y="1" width="2" height="14" rx="1"/>
                                <path d="M7.70710678,15.7071068 C7.31658249,16.0976311 6.68341751,16.0976311 6.29289322,
                                15.7071068 C5.90236893,15.3165825 5.90236893,14.6834175 6.29289322,14.2928932 L11.2928932,
                                9.29289322 C11.6689749,8.91681153 12.2736364,8.90091039 12.6689647,9.25670585 L17.6689647,
                                13.7567059 C18.0794748,14.1261649 18.1127532,14.7584547 17.7432941,15.1689647 C17.3738351,
                                15.5794748 16.7415453,15.6127532 16.3310353,15.2432941 L12.0362375,11.3779761 L7.70710678,
                                15.7071068 Z" fill="#000000" fill-rule="nonzero" transform="translate(12.000004, 12.499999) rotate(-180.000000) translate(-12.000004, -12.499999) "/>
                            </g>
                        </svg>
                    </span>				
                </a>
                <a href="javascript:;" @click="previewFile()" class="btn btn-sm btn-clean btn-icon" title="预览" >	
                    <span class="svg-icon svg-icon-primary svg-icon-2x">
                        <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24px" height="24px" viewBox="0 0 24 24" version="1.1">
                            <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                                <rect x="0" y="0" width="24" height="24"/>
                                <path d="M10,6 L14.5,6 C16.709139,6 18,7.290861 18,9.5 L18,14 L16,14 L16,9.5 C16,8.3954305 15.6045695,
                                8 14.5,8 L10,8 L10,6 Z M8,6 L8,8 L4,8 C3.44771525,8 3,7.55228475 3,7 C3,6.44771525 3.44771525,6 4,
                                6 L8,6 Z M18,16 L18,20 C18,20.5522847 17.5522847,21 17,21 C16.4477153,21 16,20.5522847 16,20 L16,16 L18,16 Z" fill="#000000" fill-rule="nonzero" opacity="0.3"/>
                                <path d="M7,5 C6.44771525,5 6,4.55228475 6,4 C6,3.44771525 6.44771525,3 7,3 L17.5,3 C19.709139,
                                3 21,4.290861 21,6.5 L21,17 C21,17.5522847 20.5522847,18 20,18 C19.4477153,18 19,17.5522847 19,
                                17 L19,6.5 C19,5.3954305 18.6045695,5 17.5,5 L7,5 Z" fill="#000000" fill-rule="nonzero" transform="translate(13.500000, 10.500000) rotate(-180.000000) translate(-13.500000, -10.500000) "/>
                            </g>
                        </svg>
                    </span>
                </a>
                <a href="javascript:;" @click="copyFile()" class="btn btn-sm btn-clean btn-icon" title="复制地址" >	
                    <span class="svg-icon svg-icon-primary svg-icon-2x">
                        <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24px" height="24px" viewBox="0 0 24 24" version="1.1">
                            <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                                <rect x="0" y="0" width="24" height="24"/>
                                <path d="M6,9 L6,15 C6,16.6568542 7.34314575,18 9,18 L15,18 L15,18.8181818 C15,20.2324881 14.2324881,
                                21 12.8181818,21 L5.18181818,21 C3.76751186,21 3,20.2324881 3,18.8181818 L3,11.1818182 C3,
                                9.76751186 3.76751186,9 5.18181818,9 L6,9 Z M17,16 L17,10 C17,8.34314575 15.6568542,7 14,7 L8,7 L8,6.18181818 C8,4.76751186 8.76751186,4 10.1818182,4 L17.8181818,4 C19.2324881,4 20,4.76751186 20,6.18181818 L20,13.8181818 C20,15.2324881 19.2324881,16 17.8181818,16 L17,16 Z" fill="#000000" fill-rule="nonzero" opacity="0.3"/>
                                <path d="M9.27272727,9 L13.7272727,9 C14.5522847,9 15,9.44771525 15,10.2727273 L15,14.7272727 C15,
                                15.5522847 14.5522847,16 13.7272727,16 L9.27272727,16 C8.44771525,16 8,15.5522847 8,14.7272727 L8,
                                10.2727273 C8,9.44771525 8.44771525,9 9.27272727,9 Z" fill="#000000"/>
                            </g>
                        </svg>
                    </span>
                </a>                
                <a href="javascript:;" @click="deleteFile()" v-if="canDelete == true" class="btn btn-sm btn-clean btn-icon" title="清空" >	
                    <span class="svg-icon svg-icon-primary svg-icon-2x">
                        <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24px" height="24px" viewBox="0 0 24 24" version="1.1">
                            <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                                <rect x="0" y="0" width="24" height="24"/>
                                <rect fill="#000000" opacity="0.3" x="2" y="4" width="20" height="5" rx="1"/>
                                <path d="M5,7 L8,7 L8,21 L7,21 C5.8954305,21 5,20.1045695 5,19 L5,7 Z M19,7 L19,19 C19,
                                20.1045695 18.1045695,21 17,21 L11,21 L11,7 L19,7 Z" fill="#000000"/>
                            </g>
                        </svg>
                    </span>
                </a>
            </b-card-text>
        </b-card>
        <FileUpload ref="fileUploadRef" @change="setFileUpload" :fileOpt="{fileOpt}"></FileUpload>
        <JEHCPDF ref="jehcPdfRef"></JEHCPDF>
        <JEHCImagePreview ref="jehcImagePreviewRef"></JEHCImagePreview>
    </div>
</template>

<script>
import apiUtil from "@/core/util/apiUtil.js";
import tokenUtil from "@/core/util/tokenUtil.js";
import FileUpload from "@/components/file-upload.vue";
import JEHCImagePreview from "@/components/jehc-image-preview.vue";
import JEHCPDF  from "@/components/jehc-pdfjs.vue";
import { handleNotify, handleAlert, handleConfirm, showWating, closeWating,createXHR,downloadFileCallFn, isImageByType } from "@/core/util/jehcUtil.js";
export default {
    data() {
        return {
            canUpload:true,
            canDelete:true,
            fileWidgetForm: {
                id: "",
                attachmentPic: process.env.BASE_URL + "images/add_d.png",
            },
            // 菜单数据
            contextMenuData: {
                menuName: 'demo',
                //菜单显示的位置
                axis: {
                    x: null,
                    y: null
                },
                //菜单选项
                menulists: [{
                    fnHandler: 'showFileUpload', //绑定事件
                    icoName: 'fas fa-file-upload', //icon图标
                    disabled: this.disabledUpload,
                    btnName: '上传' //菜单名称
                }, {
                    fnHandler: 'downloadFile', //绑定事件
                    icoName: 'fas fa-download', //icon图标
                    btnName: '下载' //菜单名称
                }, {
                    fnHandler: 'copyFile', //绑定事件
                    icoName: 'far fa-copy', //icon图标
                    btnName: '复制地址' //菜单名称
                }, {
                    fnHandler: 'previewFile', //绑定事件
                    icoName: 'far fa-eye-slash', //icon图标
                    btnName: '预览' //菜单名称
                }, {
                    fnHandler: 'deleteFile',
                    icoName: 'fas fa-trash-alt',
                    disabled: this.disabledDelete,
                    btnName: '清空'
                }]
            }
        }
    },
    components: {
        FileUpload,
        JEHCPDF,
        JEHCImagePreview,
    },
    props: {//通过props接收传递参数
        fileOpt: []
    },
    watch: {
        fileOpt: {
            immediate: true,//必须加上否则没法进入监控变化
            deep: true,//必须加上否则没法监控属性值的改变而进入该方法
            handler(val) {  
                this.fileOpt = val;                     
                this.callbackFn();
            }
        }
    },
    mounted() {

    },
    methods: {    
        callbackFn(){
            if(null != this.fileOpt && null != this.fileOpt.value){   
                this.initCanOpt(this.fileOpt);
                let value =  this.fileOpt.value;
                let field = this.fileOpt.field;                   
                if(undefined === field || null === field || "" === field){
                    field = "attachmentId";
                }
                if(undefined != value && null != value && "" != value){     
                    apiUtil.post(process.env.VUE_APP_FILE_API+"/attAchmentPathpp",{id:value,fieldName:field}).then(({ data }) => {
                        if(null != data && null != data.data && data.data.length>0){
                            let fileType = data.data[0].fileType;
                            let jsonValue = data.data[0].path;
                            if (isImageByType(fileType)) {
                                this.fileWidgetForm.attachmentPic = jsonValue;
                            } else {//非图片
                                this.fileWidgetForm.attachmentPic = process.env.BASE_URL + "images/upload_success.png"
                            }
                            this.fileWidgetForm.id = value;
                        }else{
                            handleAlert("文件不存在", "warning", 3)
                        }                     
                    });
                }
            }
        },
        initCanOpt(){//初始化判断控件项是否禁用 必然新建 编辑 都可以进行上传 和清空操作 而详情不可以
            if(undefined != this.fileOpt.upload){
                this.canUpload = this.fileOpt.upload;
            }
            if(null != this.fileOpt.delete){
                this.canDelete = this.fileOpt.delete;
            }
        },
        setFileUpload(res, callData) {//回调设置值
            let fileType = res.data.fileType;
            let jsonValue = res.data.jsonValue;
            let jsonID = res.data.jsonID;
            if (isImageByType(fileType)) {
                this.fileWidgetForm.attachmentPic = jsonValue;
            } else {//非图片
                this.fileWidgetForm.attachmentPic = process.env.BASE_URL + "images/upload_success.png"
            }
            if (jsonID != 0) {
                this.fileWidgetForm.id = jsonID;
                this.$emit("change", res, this.fileOpt);//组件传值，即向父级模态框中传递值，采用change方式，目标刷新主列表使用
            }
            console.log("----将接收的参数进行回调---", res, this.fileOpt);
        },        
        showMenu() {
            event.preventDefault()
            var x = event.clientX
            var y = event.clientY
            // Get the current location
            this.contextMenuData.axis = {
                x, y
            }
        },
        restForm() {
            //重置
        },
        showFileUpload() {//通用调用附件上传方法
            if(this.canDelete == false){
                handleAlert("不可操作", "warning", 3)
                return;
            }
            this.$refs.fileUploadRef.showModal()
        },
        downloadFile(){
            let id = this.fileWidgetForm.id;
            if(null != id && "" != id){
                showWating({ renderBody: "fileWidgetBody",message:"验证文件..." });
                apiUtil.get(process.env.VUE_APP_FILE_API+"/attachment/get/"+id).then(({ data }) => {                
                    let fileName = data.data.title; // 下载后的文件名称
                    let params = "name='test" // 后台接口需要的参数
                    let url = process.env.VUE_APP_FILE_API+'/downFile?id='+id; // 请求接口
                    let method = "GET"; // 请求方式 GET或POST
                    downloadFileCallFn(url, method, fileName,params);
                });
            }else{
                handleAlert("文件不存在", "warning", 3)
                return;
            }
            console.log('downloadFile!')
        },
        copyFile(){
            let urlPath = this.fileWidgetForm.attachmentPic;
            let id = this.fileWidgetForm.id;
            if(null != id && "" != id){
            }else{
                handleAlert("文件不存在", "warning", 3)
                return;
            }            
            handleNotify ('复制地址', "文件地址："+urlPath, '类型', 'top-right','5000')
        },
        deleteFile() {
            if(this.canDelete == false){
                handleAlert("不可操作", "warning", 3)
                return;
            }
            let id = this.fileWidgetForm.id;
            if(null != id && "" != id){
            }else{
                handleAlert("文件不存在", "warning", 3)
                return;
            }
            this.fileWidgetForm.attachmentPic =  process.env.BASE_URL + "images/add_d.png";
            let res = {};
            res.data = {};
            res.data.jsonID = "";
            this.fileOpt.value = "";
            this.$emit("change", res, this.fileOpt);//组件传值，即向父级模态框中传递值，采用change方式，目标刷新主列表使用
        },
        previewFile(){
            let thiz = this;   
            let id = this.fileWidgetForm.id;
            let token = `${tokenUtil.getToken()}`;
            if(null != id && "" != id){
                showWating({ renderBody: "fileWidgetBody",message:"验证文件..." });
                apiUtil.get(process.env.VUE_APP_FILE_API+"/attachment/get/"+id).then(({ data }) => {                
                    let title = data.data.title;
                    let point = title.lastIndexOf(".");
                    let type = title.substr(point);
                    if(type==".doc"||type==".docx"||type==".xls"||type==".xlsx"|| type==".ppt"||type==".pptx"||type==".csv"){
                        //文件
                        let httpUrl = process.env.VUE_APP_FILE_API+'/preview/'+id; // 请求接口
                        let method = "GET";
                        let xhr = createXHR();// 创建ajax异步对象
                        if(null == xhr){
                            return;
                        }
                        xhr.timeout = 30000000;
                        xhr.ontimeout = function (event) {
                            handleAlert("请求超时...", "warning", 3)
                        }
                        handleAlert("开始加载文件流...", "info", 3)
                        showWating({ renderBody: "fileWidgetBody",message:"正在加载文件流..." });
                        if(method.toLowerCase() == "post"){//POST
                            xhr.open("POST",httpUrl,true);
                            xhr.setRequestHeader("token", token);//设置header
                            xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                            xhr.send();// 发送请求
                        }else{//GET
                            xhr.open(method, httpUrl, true);
                            xhr.setRequestHeader("token", token);//设置header
                            xhr.send();// 发送请求
                        }
                        xhr.responseType = "blob"; // 设置响应类型为 blob形式
                        var URL = window.URL || window.webkitURL;
                        xhr.onreadystatechange = function (res) {// 响应
                            if (xhr.readyState === 4) {
                                if (xhr.status === 200) { // 响应成功
                                    var blobText = xhr.response; // 将返回的二进制流文件转换为blob形式的
                                    var url = window.URL || window.webkitURL;
                                    var blobUrl = url.createObjectURL(blobText); // 设置href,URL.createObjectURL(blobText) 将blob读取成一个url                            
                                    thiz.$refs.jehcPdfRef.showModal(blobUrl);
                                    
                                    handleAlert("加载文件流完毕！", "success", 3)
                                } else {
                                    handleAlert("加载文件流失败！", "error", 3)
                                }
                            }
                        };
                    }else{
                        //图片
                        thiz.getBimghw(thiz.fileWidgetForm.attachmentPic,thiz);
                    }
                });
            }else{
                handleAlert("文件不存在", "warning", 3)
                return;
            }
        },
        getBimghw(src,thiz){
            let imageAttribute = [];
            try{     
                let img_url = src+'?'+Date.parse(new Date());
                //创建对象
                let img = new Image();
                //改变图片的src
                img.src = img_url;
                // 加载完成执行
                let w =260;
                let h =200;      

                img.onload = function(){
                    
                    w = img.width;
                    h = img.height;
                    if(h > 400){
                        h = 400;
                    }else{
                        h = 200;
                    }

                    if(w>1000){
                        w = 708;
                    }else{
                        w = 260;
                    }
                    imageAttribute.w = w;
                    imageAttribute.h = h; 
                    imageAttribute.url = img_url;
                    thiz.$refs.jehcImagePreviewRef.showModal(imageAttribute);
                    return imageAttribute;
                };
                img.onerror = function(){
                    handleAlert("该图片不能预览", "warning", 3)
                    return imageAttribute;
                };
            }catch(e){
                //非法即不满足图片
                handleAlert("该图片不能预览", "warning", 3);
                return imageAttribute;
            }
        },
    }
}
</script>
